var objMarker;
var map;

function add_marker(lat, lng, title, box_html) {
    var infowindow = new google.maps.InfoWindow({
        content: box_html
    });
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        title: title
    });
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });
 
    return marker;
}


function ShowClusters(viewport,pointsType){
	
  function callback(json) {
    if (json.status == 'OK') {
      var markers = [];
      for (var i = 0; i < json.markers.length; i++) {
		var baloon = '<div><a href="item.php?id=' + json.markers[i].id + '">' + json.markers[i].title + '</a><\/div>';
		var marker = add_marker(json.markers[i].lat,json.markers[i].lon, json.markers[i].title, baloon);
        markers.push(marker);
      }
      var markerCluster = new MarkerClusterer(map, markers);
    } else {
      //alert('Произошла ошибка!');
    }
  }
  if (!pointsType)
	  pointsType = "all";
	  
  var pointsURL = "/getpoints.php?box="+viewport.toUrlValue()+"&ptype="+pointsType;
  $.getJSON(pointsURL,callback);
/*
  $.ajax({
    dataType: "json",
    url: "getpoints.php",
    //data: data,
    success: callback
  });
*/
}


function initialize_map1(elRegSelID,location,place_name,viewport,point,cluster,editable,type_points) {
	var elRegSel = document.getElementById(elRegSelID);
    
	
	var options =
        {
          level:    '(regions)',   // level (region | subregion | city)
          lang: 'ru',
          sensor: 'true'
        };
	function callback(predictions, status) {
		if (status != google.maps.places.PlacesServiceStatus.OK) {
			return;
		}
		var service = new google.maps.places.PlacesService(map);
		service.getDetails({reference: predictions[0].reference }, 
			function(place, status) {
				if (status == google.maps.places.PlacesServiceStatus.OK) {
					elRegSel.innerHTML = place.formatted_address;
					if (map) {
						map.fitBounds(place.geometry.viewport);
						ShowClusters(place.geometry.viewport, type_points);
					}
					deleteCookie('geolocation_viewport');
					deleteCookie('geolocation_location');
					deleteCookie('geolocation_place');

					setCookie('geolocation_viewport',place.geometry.viewport.toString(),{ expires: 7776000 });
					setCookie('geolocation_location',place.geometry.location.toString(),{ expires: 7776000 });
					setCookie('geolocation_place',place.formatted_address,{ expires: 7776000 });
				}
			});
	}

	var zoomm = 8;
	//преобразуем location в LatLng
	if (typeof(location) == 'string'){
		location = location.substring(1, location.length-1).split(",");
		if (location.length > 2)
			zoomm = parseInt(location[2]);
		location = new google.maps.LatLng(parseFloat(location[0]), parseFloat(location[1]));
	};
		
	var dCur = '';
	if (editable)
		dCur = 'url(/images/siteM16.png) 21 21, default';
	var mapOptions = {
		center : location,
		zoom : zoomm,
		scrollwheel: editable,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		//draggableCursor: 'crosshair'
		draggableCursor: dCur
	};
	if (document.getElementById("map_canvas"))
		map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	//определить viewport, если не задан
	if (viewport) {
		if (viewport == 'init') {
			var PName = new google.maps.places.AutocompleteService();
			PName.getPlacePredictions({input: elRegSel.innerHTML /*Text*/, types: [options['level']], language: options['lang'], sensor: options['sensor']}, callback);
		} else {
			if (typeof(viewport) == 'string'){
				viewport = viewport.replace(/[()]+/g,'');
				viewport = viewport.split(',');
				viewport = new google.maps.LatLngBounds((new google.maps.LatLng(parseFloat(viewport[0]), parseFloat(viewport[1]))),
														(new google.maps.LatLng(parseFloat(viewport[2]), parseFloat(viewport[3]))));
			if (map)
				map.fitBounds(viewport);
			};

		}
	}

	//если задана точка...
	if (point && map) {
		objMarker = new google.maps.Marker({
			map : map,
			draggable : editable,
			position : location
		});
	}

	if (editable && map)
		google.maps.event.addListener(map, 'click', function(event) {
			createMarker(event.latLng,true);});
	

	if (cluster && viewport && !(viewport == 'init'))
		ShowClusters(viewport, type_points);
};


function createMarker(location,editable) {
	var pos;
	var elObjMarker = document.getElementById("objMarkerCoord");

	if (objMarker == null){
		objMarker = new google.maps.Marker({
			map : map,
			draggable : editable,
			animation : google.maps.Animation.DROP,
			position : location
		});
		}
	else{
		objMarker.setPosition(location);
		}
	pos = objMarker.getPosition();
	elObjMarker.value = pos.lat() + "," + pos.lng() + "," + map.getZoom();
	//elObjMarker.value = pos.toString();
	
}



